package com.w.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.w.util.B64.b64tohex;
import static com.w.util.B64.hex2b64;
import static com.w.util.RSAEncoder.RSAEncrypt;

public class ConnectJWGL {

    private final static String url = "http://www.zfjw.xupt.edu.cn";
    private Map<String,String> cookies = new HashMap<>();
    private String modulus;
    private String exponent;
    private String csrftoken;
    private Connection connection;
    private Connection.Response response;
    private Document document;
    private String stuNum;
    private String password;

    public ConnectJWGL(String stuNum,String password){
        this.stuNum = stuNum;
        this.password = password;
    }

    public Map<String,String> init() throws Exception{
        getCsrftoken();
        getRSApublickey();
       return beginLogin();
    }

    // 获取csrftoken和Cookies
    private void getCsrftoken(){
        try{
            connection = Jsoup.connect(url+ "/jwglxt/xtgl/login_slogin.html?language=zh_CN&_t="+System.currentTimeMillis());
            connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
            response = connection.timeout(5000).execute();
            cookies = response.cookies();
            document = Jsoup.parse(response.body());
            csrftoken = document.getElementById("csrftoken").val();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    // 获取公钥并加密密码
    private void getRSApublickey() throws Exception{
        connection = Jsoup.connect(url+ "/jwglxt/xtgl/login_getPublicKey.html?" +
                "time="+ System.currentTimeMillis());
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        response = connection.cookies(cookies).ignoreContentType(true).timeout(5000).execute();
        JSONObject jsonObject = JSON.parseObject(response.body());
        modulus = jsonObject.getString("modulus");
        exponent = jsonObject.getString("exponent");
        password = RSAEncrypt(password, b64tohex(modulus), b64tohex(exponent));
        password = hex2b64(password);
    }

    //登录
    public Map<String,String> beginLogin() throws Exception{
        connection = Jsoup.connect(url+ "/jwglxt/xtgl/login_slogin.html");
        connection.header("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        connection.data("csrftoken",csrftoken);
        connection.data("yhm",stuNum);
        connection.data("mm",password);
        connection.data("mm",password);
        response = connection.cookies(cookies).ignoreContentType(true)
                .method(Connection.Method.POST).execute();
        cookies = response.cookies();
        response = connection.execute();
        document = Jsoup.parse(response.body());
        if(document.getElementById("tips") == null){
            return cookies;
        }else{
            HashMap mag = new HashMap();
            mag.put("JSESSIONID","error");
            mag.put("msg",document.getElementById("tips").text());
            return mag;
        }
    }


    public static Map getStudentInfo(int year , int term,Map<String,String> cookies) {
        Connection connection = Jsoup.connect(url+ "/jwglxt/kbcx/xskbcx_cxXsKb.html?gnmkdm=N2151");
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        connection.data("xnm",String.valueOf(year));
        connection.data("xqm",String.valueOf(term * term * 3));
        Connection.Response response = null;
        try {
            response = connection.cookies(cookies).method(Connection.Method.POST).ignoreContentType(true).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        HashMap<String,String> map = new HashMap();
        JSONObject jsonObject = JSON.parseObject(response.body());
        JSONObject xsxx = jsonObject.getJSONObject("xsxx");
        map.put("班级 ",xsxx.getString("BJMC"));
        map.put("学号 ",xsxx.getString("XH"));
        map.put("姓名 ",xsxx.getString("XM"));
        return map;
    }

    public static Map getStudentTimetable(int year , int term,Map<String,String> cookies) {
        Connection connection = Jsoup.connect(url+ "/jwglxt/kbcx/xskbcx_cxXsKb.html?gnmkdm=N2151");
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        connection.data("xnm",String.valueOf(year));
        connection.data("xqm",String.valueOf(term * term * 3));
        try {
            Connection.Response response = connection.cookies(cookies).method(Connection.Method.POST).ignoreContentType(true).execute();
            JSONObject jsonObject = JSON.parseObject(response.body());
            HashMap<String,String> map2 = new HashMap<>();
            if(jsonObject.get("kbList") == null){
                map2.put("msg","该学年/学期暂时没有安排课程");
                return map2;
            }
            JSONArray timeTable = JSON.parseArray(jsonObject.getString("kbList"));
            ArrayList<HashMap> list = new ArrayList(15);
            for (Iterator iterator = timeTable.iterator(); iterator.hasNext();) {
                HashMap<String,String> map = new HashMap<>();
                JSONObject lesson = (JSONObject) iterator.next();
                map.put("星期几",lesson.getString("xqj"));
                map.put("课程",lesson.getString("kcmc"));
                map.put("节/周:","("+lesson.getString("xqjmc")+" "+lesson.getString("jc")+")"+lesson.getString("zcd"));
                map.put("上课地点: ",lesson.getString("xqmc")+" "+lesson.getString("cdmc"));
                map.put("教师: ",lesson.getString("xm"));
                map.put("教学班名称:",lesson.getString("jxbmc"));
                map.put("考核方式:",lesson.getString("khfsmc"));
                map.put("选课备注:",lesson.getString("kcxz"));
                map.put("课程学时组成：",lesson.getString("kcxszc"));
                map.put("周学时: ",lesson.getString("xf"));
                map.put("总学时: ",lesson.getString("zxs"));
                map.put("学分: ",lesson.getString("xf"));
                list.add(map);
            }
            HashMap<String,ArrayList<HashMap>> map1 = new HashMap();
            map1.put("list",list);
            return map1;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}



